/*
 * @Author: silence
 * @Date: 2022-08-05 10:37:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-22 13:51:10
 * @Description: 处理网络缓存
 */

import 'dart:convert' as convert;

import 'package:dio/dio.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../utils/sputils/SpUtils.dart';

class NetCacheManager {
  static NetCacheManager _instance = NetCacheManager._internal();
  factory NetCacheManager() => _instance;
  NetCacheManager._internal();

  /// 缓存数据
  Future<bool> saveCacheData(String cacheKey, Response response,
      {int page = 1}) async {
    bool success = false;
    Map<String, dynamic> result;
    List tempResult = [];

    var data = response.data;
    if (data is String) {
      result = convert.json.decode(data);
    } else {
      result = data as Map<String, dynamic>;
    }

    // 获取缓存数据
    String? tempData = SpUtils.getData(cacheKey);
    if (!SilTools.stringIsEmpty(tempData)) {
      tempResult = convert.jsonDecode(tempData!);
    }

    if (!SilTools.listIsEmpty(result['data']) ||
        !SilTools.mapIsEmpty(result['data'])) {
      tempResult.add(result['data']);
      success =
          await SpUtils.saveData(cacheKey, convert.jsonEncode(tempResult));

      /// 获取当前页数
      Map<String, dynamic>? requestParam = response.requestOptions.data; // 接口参数
      if (requestParam != null && requestParam.containsKey('page')) {
        page = requestParam['page'];
      }
      SilLog.e("------------------保存,key为$cacheKey的第$page页缓存数据-------------");
    }

    return success;
  }

  /// 获取数据
  List getCacheData(String cacheKey, int? page, int pageLimit) {
    String? cacheData = SpUtils.getData(cacheKey);
    List pageList = [];
    if (!SilTools.stringIsEmpty(cacheData)) {
      List cacheList = convert.jsonDecode(cacheData!);

      // page为null,表示返回所有的数据
      if (page == null) {
        return cacheList;
      }

      int pageIndex = pageLimit * (page - 1); // 初始
      int pageIndexMax = pageLimit * page; // 最大
      if (cacheList.length >= pageIndexMax) {
        pageList = cacheList.sublist(pageIndex, pageIndexMax);
        SilLog.e("------------------获取,key为$cacheKey的第$page页缓存数据-------------");
      }
    }

    return pageList;
  }

  /// 清空缓存数据
  Future<bool> cleanCache(String cacheKey) async =>
      await SpUtils.saveData(cacheKey, '');
}
